import os,os.path
import sys
import getopt
import fnmatch
import shutil

def VisitDir(arg,dirname,names):
  global sourd
  for filename in names:
    if fnmatch.fnmatch(filename, '*.d'):              #for .d dependence files
      s = os.path.join(dirname,filename)
      d = s.replace(sourd,arg)
      if os.path.isdir(os.path.dirname(d)):
        shutil.copy2(s,d)
      else:
        print 'dir %s is not exist !' % os.path.dirname(d)

    if fnmatch.fnmatch(filename, '.*.o.cmd'):           # for kernel dependence file   
      s = os.path.join(dirname,filename)
      d = s.replace(sourd,arg)
      if os.path.isdir(os.path.dirname(d)):
        shutil.copy2(s,d)
      else:
        print 'dir %s is not exist !' % os.path.dirname(d) 

    if fnmatch.fnmatch(filename, '*.o'):
      s = os.path.join(dirname,filename)
      d = s.replace(sourd,arg)
      if os.path.isdir(os.path.dirname(d)):
        shutil.copy2(s,d)
      else:
        print 'dir %s is not exist !' % os.path.dirname(d)


def main(argv):
    global sourd
    sourd = ''
    destd = '' 
    try:
        opts, args = getopt.getopt(argv,"hs:d:",["sourd=","destd="])
    except getopt.GetoptError:
        print 'test.py -s <sourd> -d <destd>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'test.py -s <sourd> -d <destd>'
            sys.exit()
        elif opt in ("-s", "--sourd"):
            sourd = arg
        elif opt in ("-d", "--destd"):
            destd = arg

    if sourd == '':
        print 'sourd could not be empty'
        sys.exit(2)

    os.path.walk(sourd,VisitDir,destd) 


if __name__=="__main__":
  main(sys.argv[1:])
